package bowshot

import (
	"errors"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// Expired delete work
var (
	ErrTimeLengthInappropriate = errors.New("time length inappropriate")
)

func localTime(ts string, now time.Time) (time.Time, error) {
	var t time.Time
	if len(ts) != len("20190101-0101-00") {
		return t, ErrTimeLengthInappropriate
	}
	y, err := strconv.Atoi(ts[0:4])
	if err != nil {
		return t, err
	}
	m, err := strconv.Atoi(ts[4:6])
	if err != nil {
		return t, err
	}
	d, err := strconv.Atoi(ts[6:8])
	if err != nil {
		return t, err
	}
	h, err := strconv.Atoi(ts[9:11])
	if err != nil {
		return t, err
	}
	min, err := strconv.Atoi(ts[11:13])
	if err != nil {
		return t, err
	}
	s, err := strconv.Atoi(ts[14:16])
	if err != nil {
		return t, err
	}
	t = time.Date(y, time.Month(m), d, h, min, s, 0, now.Location())
	return t, nil
}

// RemoveExpired todo
// %04d%02d%02d-%02d%02d-%02d
// banjo.20190807-0808-04.log like this
func RemoveExpired(dir string, expires int) error {
	now := time.Now()
	es := int64(expires * 3600 * 24)
	return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return filepath.SkipDir
		}
		if info.IsDir() {
			return nil
		}
		sv := strings.Split(info.Name(), ".")
		if len(sv) < 3 {
			// skip
			return nil
		}
		t, err := localTime(sv[len(sv)-2], now)
		if err != nil {
			return nil
		}
		if now.Unix()-t.Unix() > es {
			_ = os.Remove(path)
		}
		// 422
		return nil
	})
}
